import os
import common
import time

CONF = common.load_conf(None)
HISTORIES = common.load_history(CONF)
API = common.load_api(CONF)
LOGFILE = "daemon.log"

def running():
    try:
        os.stat( common.RUN_FILE )
        return True
    except:
        return False
    return False

def _fetch(channel):
    try:
        if channel == "public":
            return api.GetPublicTimeline()
        elif channel == "friends":
            return api.GetFriendsTimeline(CONF.username)
    except:
        return None

def log( msg ):
   fp = open( LOGFILE, 'a' )
   now = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
   fp.write( "[%s] %s\n" % (now, msg) )
   fp.close()

def update():
    for chan in ('public','friends'):
        try:
            HISTORIES.get(chan).add(_fetch(chan))
            log( "Adding tweets from the %s timeline..." % chan )
        except Exception, e:
            log( "Error: %s" % e )

if __name__ == "__main__":
    log( "Starting daemon..." )
    time.sleep(15) # sleep initially to give time for the RUN_FILE to be generated
    while running():
        update()
        log("Updated. Sleeping for %d seconds..." % CONF.get_frequency())
        time.sleep(CONF.get_frequency())
